﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace VeryCodes.Common
{
    /// <summary>
    /// 该类主要用于XML的处理
    /// 需要首先实例化，才能使用相关方法
    /// </summary>
    public class XMLHelper
    {
        /// <summary>
        /// 无参构造函数
        /// </summary>
        public XMLHelper()
        {
        }

        #region 对象的序列化和反序列化(Xml格式) XmlSerialize/XmlDeserialize

        /// <summary>
        /// 将指定类型的对象序列化为XML
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="extra"></param>
        /// <returns></returns>
        /// <example>String ReturnValue=XMLHelper.XmlSerialize(arrExample,typeof([ClassName]))</example>
        public string XmlSerialize(object obj, params Type[] extra)
        {
            XmlSerializer ser = new XmlSerializer(obj.GetType(), extra);
            System.IO.MemoryStream mem = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.Default);
            ser.Serialize(writer, obj);
            string strtmp = Encoding.Default.GetString(mem.ToArray());
            return strtmp;
        }

        /// <summary>
        /// 将xml反序列化为对象
        /// </summary>
        /// <param name="xml">xml字符串</param>
        /// <param name="type">指定类型</param>
        /// <param name="extra"></param>
        /// <returns></returns>
        /// <example>ArrayList arrExample = (ArrayList)XMLHelper.XmlDeserialize(value, typeof(ArrayList), typeof([ClassName]));</example>
        public object XmlDeserialize(string xml, Type type, params Type[] extra)
        {
            XmlSerializer serializer = new XmlSerializer(type, extra);
            System.IO.MemoryStream mem;
            try
            {
                mem = new MemoryStream(Encoding.Default.GetBytes(xml));
            }
            catch
            {
                return null;
            }
            return serializer.Deserialize(mem);
        }

        /// <summary>
        /// 将DataTable序列化为xml
        /// </summary>
        /// <param name="dt">Datatable</param>
        /// <param name="tableName">设置DataTable的名称</param>
        /// <returns>xml文本</returns>
        public static string XmlSerialize(DataTable dt, string tableName)
        {
            dt.TableName = tableName;
            System.Text.StringBuilder strbuilder = new System.Text.StringBuilder();
            StringWriter writer = new StringWriter(strbuilder);
            dt.WriteXml(writer, System.Data.XmlWriteMode.IgnoreSchema);
            return strbuilder.ToString();
        }

        /// <summary>
        /// 将xml反序列化为DataTable
        /// </summary>
        /// <param name="xml">xml文本</param>
        /// <returns>DataTable</returns>
        public static DataTable XmlDeserialize(string xml)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            try
            {
                MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(xml));
                ds.ReadXml(mem);
                if (ds.Tables.Count > 0)
                    dt = ds.Tables[0];
            }
            catch
            {
                return null;
            }
            return dt;
        }
        #endregion

        #region 树状目录的解析和绑定

        /// <summary>
        /// 将xml数据绑定到树状目录
        /// 如果发生异常，则不会绑定
        /// </summary>
        /// <param name="document">单个xml节点</param>
        /// <param name="treeView">树状目录[TreeView]</param>
        /// <param name="lstPermission">允许访问树节点</param>
        public void TreeViewParse(System.Xml.XmlNode document, TreeView treeView, List<string> lstPermission)
        {
            if (document.Name != "TreeView") return;

            try
            {
                foreach (System.Xml.XmlNode node in document.ChildNodes)
                {
                    if (node.Name == "treenode")
                    {
                        if (lstPermission.IndexOf(node.Attributes["PermissionCode"].Value) >= 0 || node.Attributes["PermissionCode"].Value == "")
                            treeView.Nodes.Add(NodesParse(node, lstPermission));
                    }
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 将xml数据绑定到树状目录
        /// </summary>
        /// <param name="document">单个xml节点</param>
        /// <param name="treeView">树状目录[TreeView]</param>
        public void TreeViewParse(System.Xml.XmlNode document, TreeView treeView)
        {
            if (document.Name != "TreeView") return;
            foreach (System.Xml.XmlNode node in document.ChildNodes)
            {
                if (node.Name == "treenode")
                    treeView.Nodes.Add(NodesParse(node));
            }
        }

        /// <summary>
        /// 根据传入的xml节点，设置树节点的各项属性和子节点
        /// 如果获取XmlNode节点的值发生异常，则该节点不会添加到树中
        /// </summary>
        /// <param name="document">xml节点[XmlNode]</param>
        /// <returns>TreeNode</returns>
        private TreeNode NodesParse(System.Xml.XmlNode document)
        {
            TreeNode node = new TreeNode();

            try
            {
                node.Text = document.Attributes["text"].Value;
                node.NavigateUrl = document.Attributes["NavigateUrl"].Value;
                node.ToolTip = document.Attributes["Description"].Value;
                node.Value = document.Attributes["PermissionCode"].Value;
                if (node.NavigateUrl == "")
                    node.SelectAction = TreeNodeSelectAction.None;

                foreach (System.Xml.XmlNode node2 in document.ChildNodes)
                {
                    TreeNode node3 = NodesParse(node2);
                    if (node3 != null)
                    {
                        node.ChildNodes.Add(node3);
                    }
                }
            }
            catch
            {
                return null;
            }
            return node;
        }

        /// <summary>
        /// 根据传入的xml节点和允许访问节点列表，设置树节点的各项属性和子节点
        /// 如果获取XmlNode节点的值发生异常，则该节点不会添加到树中
        /// </summary>
        /// <param name="document">xml节点[XmlNode]</param>
        /// <param name="lstPermission">允许访问列表</param>
        /// <returns>TreeNode</returns>
        private TreeNode NodesParse(System.Xml.XmlNode document, List<string> lstPermission)
        {
            TreeNode node = new TreeNode();
            try
            {
                node.NavigateUrl = document.Attributes["NavigateUrl"].Value;
                node.Text = document.Attributes["text"].Value;
                node.ToolTip = document.Attributes["Description"].Value;
                node.Value = document.Attributes["PermissionCode"].Value;
                if (node.NavigateUrl == "")
                    node.SelectAction = TreeNodeSelectAction.None;

                foreach (System.Xml.XmlNode node2 in document.ChildNodes)
                {
                    TreeNode node3 = NodesParse(node2);
                    if (node3 != null)
                    {
                        if (lstPermission.IndexOf(node2.Attributes["PermissionCode"].Value) >= 0 || node2.Attributes["PermissionCode"].Value == "")
                            node.ChildNodes.Add(node3);
                    }
                }
            }
            catch
            {
                return null;
            }
            return node;
        }
        #endregion

        /// <summary>
        /// 获取xml文件中指定节点的指定子节点的值
        /// </summary>
        /// <param name="FilePah">xml文件</param>
        /// <param name="FindNode">指定节点</param>
        /// <param name="strKeyName">指定节点的指定子节点</param>
        /// <returns>节点值</returns>
        public string GetKeyValue(string FilePah, string FindNode, string strKeyName)
        {
            string _strKeyValue = "";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(FilePah);
            XmlNodeList nodes = xmlDoc.SelectNodes(FindNode);
            foreach (XmlNode node in nodes)
            {
                foreach (XmlNode childNode in node.ChildNodes)
                {
                    if (childNode.Name == strKeyName)
                    {
                        _strKeyValue = childNode.InnerText;
                    }
                }
            }
            return _strKeyValue;
        }
    }
}